package cn.brilliantfuture.commentry.store.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.jboss.wsf.spi.annotation.WebContext;

import cn.brilliantfuture.commentry.store.StoreKeysMessageRemote;
import cn.brilliantfuture.commentry.store.StoreKeysMessageWebService;

/**
 * 
 * Title: Communication Entry
 * 
 * Author:  LiTian  
 *
 * Date: 2013-2-6
 * 
 * Description:
 * 
 */
@Stateless
@WebService(endpointInterface = "cn.brilliantfuture.commentry.store.StoreKeysMessageWebService")
@WebContext(contextRoot = "/commentry", urlPattern = "/StoreKeysMessageWebService")
public class StoreKeysMessageImpl implements StoreKeysMessageRemote, StoreKeysMessageWebService{
	
	private static Logger logger = Logger.getLogger(StoreKeysMessageImpl.class);
	
	@PersistenceContext
	EntityManager entityManager;

	@SuppressWarnings("unchecked")
	public String queryStoreKeys(String deviceSn, int maxKeysNo) {
		logger.info("deviceSn -> " + deviceSn + " maxKeysNo -> " + maxKeysNo);
		
		JSONArray result = new JSONArray();
		
		List<Object[]> list = entityManager.createNativeQuery("select ssk.storage_service_key_id, ci.card_number, p.phone from storage_service_key ssk inner join purchaser p on p.purchaser_id = ssk.purchaser_id inner join card_info ci on p.purchaser_id = ci.purchaser_id inner join lockers l on l.lockers_id = ssk.lockers_id where ssk.enable = true and l.device_sn = '" + deviceSn + "' and ssk.storage_service_key_id > " + maxKeysNo).getResultList();
		
		if (null != list && list.size() > 0) {
			for (Object[] objs : list) {
				JSONObject obj = new JSONObject();
				
				obj.accumulate("keysNo", (Integer)objs[0]);
				obj.accumulate("userId", (String)objs[1]);
				obj.accumulate("phone", (String)objs[2]);
				obj.accumulate("boxNum", 1);
				
				result.add(obj);
			}
		}
		
		return result.toString();
	}

}
